<script setup lang="ts">
import { frequencyType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  currencyList: any = inject("currencyList", []),
  activityBaseInfo: any = inject("activityBaseInfo", {}),
  activityReadonly = inject("activityReadonly");

const form = ref<any>({
    partType: 0,
    freeType: null,
    partTotalLimit: 0,
    lotteryTotalLimit: 0,
    lotteryLimitType: 0,
  }),
  prizeAreas = ref<Array<any>>([]),
  signConfig = ref<any>({ lotteryConfig: 0 });

const formRef = ref(),
  poolRef = ref(),
  signRef = ref();

const rules = {
  lotteryTotalNum: [
    { required: true, message: "请输入中奖总次数", trigger: "blur" },
  ],
  commonRewardCoinId: [
    { required: true, message: "请选择积分类型", trigger: "change" },
  ],
  commonRewardNum: [
    { required: true, message: "请输入积分数量", trigger: "blur" },
  ],
  signCycle: [{ required: true, message: "请选择签到周期", trigger: "change" }],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const limitsDisabled = computed(() => {
  return form.value.hasTicket == 1 && activityBaseInfo.value.status == 2;
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit: null,
  });

  if (val.actSignConfig) {
    signConfig.value = val.actSignConfig;
    if (form.value.subType == "WeekSign") {
      if (signConfig.value.signType == 1) {
        signConfig.value.maxDays = signConfig.value.maxSignDays;
      } else {
        signConfig.value.maxDays = signConfig.value.maxAccuDays;
      }
    }
  } else {
    signConfig.value = Object.assign({}, signConfig.value, {
      pageFlag: form.value.pageFlag,
    });
    createSignConfig();
  }

  prizeAreas.value = val.prizeAreas || [];
  updateData();
};

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (signConfig.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

const quotePrize = computed(() => {
  let prize = (signConfig.value.itemList || []).filter((item: any) => {
    if (item.rewardEntity.rewardType === "PRIZE") {
      return true;
    }
    return false;
  });
  if (prize && prize.length > 0) {
    return prize.map((item: any) => {
      return {
        prizeId: item.rewardEntity.prizeId,
        poolId: item.rewardEntity.prizeArea,
        specId: item.rewardEntity.prizeSpec,
      };
    });
  }
  return [];
});

// 初始化签到配置
const createSignConfig = () => {
  // 周签到
  if (form.value.subType == "WeekSign") {
    signConfig.value = {
      ...signConfig.value,
      signTemplate: "LIMIT",
      commonReward: 0,
      signCycle: 4,
      signType: 1,
      maxDays: 7,
      itemList: [],
    };
    createWeekSignDay();
  }
  // 月签到
  else if (form.value.subType == "MonthSign") {
    signConfig.value = {
      ...signConfig.value,
      signTemplate: "CALENDAR",
      commonReward: 1,
      commonExclusive: 1,
      commonRewardType: "COIN",
      signCycle: 1,
      signType: 1,
      itemList: [],
    };
  }
};

// 周签到天数填充
const createWeekSignDay = () => {
  let days = signConfig.value.maxDays;
  let itemList = signConfig.value.itemList;
  if (itemList.length > days) {
    itemList.splice(days);
  } else if (itemList.length < days) {
    let difference = days - itemList.length;
    for (let i = 0; i < difference; i++) {
      itemList.push({
        dayOrder: itemList.length + 1,
        lotteryImmediate: 1,
        mediateLotteryPage: form.value.pageFlag,
        rewardEntity: { rewardNum: 1 },
      });
    }
  }
  updateData();
};

// 添加签到奖励
const addSignReward = () => {
  if (form.value.subType == "MonthSign") {
    signConfig.value.itemList.push({
      lotteryImmediate: 1,
      mediateLotteryPage: form.value.pageFlag,
      rewardEntity: { rewardNum: 1 },
    });
  }
};

// 删除签到奖励
const deleteReward = (index: number) => {
  ElMessageBox.confirm(`确认删除吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    signConfig.value.itemList.splice(index, 1);
  });
};

// 切换签到周期
const onChangeSignCycle = () => {
  //近七天签到只能选连续签到
  if (signConfig.value.signCycle == 4) {
    signConfig.value.signType = 1;
  }
};

// 切换是否开启抽奖
const onChangeLotteryConfig = () => {
  if (signConfig.value.lotteryConfig == 0) {
    signConfig.value.itemList.forEach((item: any) => {
      if (item.rewardEntity.rewardType === "LOTTERY") {
        item.rewardEntity.rewardType = "";
        item.rewardEntity.lotteryArea = "";
        item.rewardEntity.lotteryAreaUid = "";
      }
    });
  }
  updateData();
};

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

// 添加奖池奖品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actSignConfig: signConfig.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let actSignConfig = {};
        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        // 无参与消耗自动填充免费次数
        detail.freeNum = null;
        detail.freeType = null;

        try {
          // 签到区域
          actSignConfig = await checkSign();
          // 检查奖池
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actSignConfig: actSignConfig,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

const checkSign = (): any => {
  return new Promise((resolve, reject) => {
    signRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(signConfig.value);
        let reward = false;
        for (let i = 0; i < detail.itemList.length; i++) {
          let item = detail.itemList[i];
          item.signType = signConfig.value.signType;
          if (item.rewardEntity.lotteryAreaUid)
            item.rewardEntity.lotteryArea = "";
          if (item.rewardEntity.prizeAreaUid) item.rewardEntity.prizeArea = "";
          if (item.rewardEntity.prizeUid) item.rewardEntity.prizeId = "";
          if (item.rewardEntity.prizeSpecUid) item.rewardEntity.prizeSpec = "";
          if (item.rewardEntity.ticketAct === "local")
            item.rewardEntity.ticketAct = "";
          if (item.rewardEntity.rewardType !== "NONE") reward = true;
        }
        if (!reward) {
          reject(`${form.value.name}未配置奖励`);
        }
        // 七日内签到：最大累计签到天数、最大连续签到天数字段赋值
        if (form.value.subType == "WeekSign") {
          if (detail.signType == 1) {
            detail.maxSignDays = detail.maxDays;
            detail.maxAccuDays = null;
          } else {
            detail.maxSignDays = null;
            detail.maxAccuDays = detail.maxDays;
          }
        }
        resolve(detail);
      } else reject(`请检查${form.value.name}`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="auto"
    :disabled="activityReadonly"
  >
    <template v-if="showPrizePool">
      <h3 class="collpase-title">中奖限制</h3>
      <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
        <el-radio-group v-model="form.lotteryTotalLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
        <template v-if="form.lotteryTotalLimit == 1">
          <el-form-item label-width="10px" prop="lotteryTotalNum">
            <EasyNumberInput
              v-model="form.lotteryTotalNum"
              :min="1"
              :max="9999"
              :precision="0"
              unit="次"
            />
          </el-form-item>
        </template>
      </el-form-item>
      <el-form-item label="中奖次数：">
        <el-radio-group v-model="form.lotteryLimitType">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.lotteryLimitType == 1">
        <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
          每人&nbsp;&nbsp;
          <el-select
            v-model="limit.type"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="(item, key) in frequencyType"
              :label="item"
              :value="Number(key)"
            /> </el-select
          >&nbsp;&nbsp; 最多
          <el-form-item
            label-width="10px"
            :prop="`lotteryLimit.${index}.limitNum`"
            :rules="[
              { required: true, message: '请填写限制次数', trigger: 'blur' },
            ]"
          >
            <EasyNumberInput
              v-model="limit.limitNum"
              :min="1"
              :max="9999"
              unit="次"
              :precision="0"
            ></EasyNumberInput>
          </el-form-item>
        </div>
      </el-form-item>
    </template>
  </el-form>
  <el-form
    ref="signRef"
    :model="signConfig"
    :rules="rules"
    label-width="auto"
    :disabled="activityReadonly"
  >
    <h3 class="collpase-title">签到配置</h3>
    <el-form-item label="配置抽奖：">
      <el-switch
        v-model="signConfig.lotteryConfig"
        inline-prompt
        active-text="是"
        inactive-text="否"
        :active-value="1"
        :inactive-value="0"
        :disabled="limitsDisabled"
        @change="onChangeLotteryConfig"
      />
    </el-form-item>
    <!-- 月签到配置 -->
    <el-form-item v-if="form.subType == 'MonthSign'" label="常规奖励：">
      每日签到获得
      <el-form-item label-width="10px" prop="commonRewardNum">
        <EasyNumberInput
          v-model="signConfig.commonRewardNum"
          :min="1"
          :max="9999"
          unit="个"
          :precision="0"
        />
      </el-form-item>
      <el-form-item label-width="10px" prop="commonRewardCoinId">
        <el-select
          v-model="signConfig.commonRewardCoinId"
          placeholder="请选择"
          style="width: 100px"
        >
          <el-option
            v-for="(item, key) in currencyList"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="签到周期：" prop="signCycle">
      <el-select
        v-model="signConfig.signCycle"
        placeholder="请选择"
        :disabled="limitsDisabled"
        @change="onChangeSignCycle"
      >
        <!-- 月签到配置 -->
        <el-option label="活动期间" :value="1" />
        <el-option label="每自然月" :value="2" />
        <!-- 周签到配置 -->
        <template v-if="form.subType == 'WeekSign'">
          <el-option label="每周" :value="3" />
          <el-option label="近7天" :value="4" />
        </template>
      </el-select>
    </el-form-item>
    <el-form-item label="签到类型：">
      <el-radio-group
        v-model="signConfig.signType"
        :disabled="limitsDisabled"
      >
        <el-radio :label="1">连续签到</el-radio>
        <template v-if="signConfig.signCycle != 4">
          <el-radio :label="2">累计签到</el-radio>
        </template>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="form.subType == 'WeekSign'" label="签到奖励：">
      每人最多{{ signConfig.signType == 1 ? "连续" : "累计" }}签到
      <el-form-item label-width="10px" prop="maxDays">
        <el-select
          v-model="signConfig.maxDays"
          placeholder="请选择"
          style="width: 100px"
          @change="createWeekSignDay"
        >
          <el-option v-for="num in 5" :label="2 + num" :value="2 + num" />
        </el-select>
        &nbsp;&nbsp;天
      </el-form-item>
    </el-form-item>
    <el-form-item v-for="(item, index) in signConfig.itemList">
      第
      <el-form-item
        label-width="10px"
        :prop="`itemList.${index}.dayOrder`"
        :rules="[
          {
            required: true,
            message: '请输入天数',
            trigger: 'blur',
          },
        ]"
      >
        <EasyNumberInput
          v-model="item.dayOrder"
          :min="1"
          :max="31"
          unit="天"
          :precision="0"
          :disabled="form.subType === 'WeekSign'"
          style="width: 150px"
        />
      </el-form-item>
      &nbsp;&nbsp;可获得
      <RewardSelector
        v-model="signConfig.itemList[index].rewardEntity"
        :subType="form.subType"
        :lottery="signConfig.lotteryConfig == 1 ? true : false"
        :prizeAreas="prizeAreas"
        :prefix="`itemList.${index}.rewardEntity.`"
        @change="updateData"
        @addPool="addPool"
        @addPrize="addPoolPrize"
      />
      <el-button
        v-if="form.subType == 'MonthSign'"
        type="primary"
        icon="delete"
        circle
        style="margin-left: 10px"
        @click="deleteReward(index)"
      ></el-button>
    </el-form-item>
    <el-form-item v-if="form.subType == 'MonthSign'"
      ><el-button type="primary" icon="plus" @click="addSignReward"
        >添加签到奖励</el-button
      ></el-form-item
    >
  </el-form>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="showPrizePool ? [1, 2] : [2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    :quote="quotePrize"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
